﻿namespace Refract.Navigation
{
    using System;
    using System.Windows;
    using System.Windows.Browser;
    using System.Windows.Interop;

    using Refract.Event;

    /// <summary>
    /// Implements core navigation functions
    /// </summary>
    public class NavigationProvider : INavigationProvider
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="NavigationProvider"/> class.
        /// </summary>
        public NavigationProvider()
        {
            Application.Current.Host.NavigationStateChanged += Host_NavigationStateChanged;
        }

        #endregion Constructors

        #region Events

        /// <summary>
        /// Occurs when the bookmark (hash) in the browser url changes.
        /// </summary>
        public event EventHandler<EventArgs<String>> BookMarkChanged;

        #endregion Events

        #region Properties

        /// <summary>
        /// Gets the current bookmark (url hash #).
        /// </summary>
        /// <value>The current bookmark.</value>
        public string CurrentBookmark
        {
            get { return HtmlPage.Window.CurrentBookmark; }
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Navigates to a bookmark (url hash #).
        /// </summary>
        /// <param name="pageName">Name of the page.</param>
        public void NavigateToBookmark(string pageName)
        {
            HtmlPage.Window.NavigateToBookmark(pageName);
        }

        /// <summary>
        /// Handles the NavigationStateChanged event of the Host control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Interop.NavigationStateChangedEventArgs"/> instance containing the event data.</param>
        private void Host_NavigationStateChanged(object sender, NavigationStateChangedEventArgs e)
        {
            if (BookMarkChanged != null)
            {
                BookMarkChanged(sender, new EventArgs<String>(e.NewNavigationState));
            }
        }

        #endregion Methods
    }
}